package so.shanku.essential.activity;

import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import aym.util.getservicesdata.GetServicesDataQueue;
import aym.util.getservicesdata.GetServicesDataUtil;
import aym.util.json.JsonMap;
import aym.util.json.JsonParseHelper;
import net.tsz.afinal.annotation.view.ViewInject;
import so.shanku.essential.R;
import so.shanku.essential.activity.base.BaseUIActivity;
import so.shanku.essential.adapter.ReturnOrderAdapter;
import so.shanku.essential.getdata.GetDataConfing;
import so.shanku.essential.getdata.GetDataQueue;
import so.shanku.essential.getdata.JsonKeys;
import so.shanku.essential.getdata.ShowGetDataError;
import so.shanku.essential.utils.Constant;
import so.shanku.essential.utils.Utils;
import striveen.util.used.view.view.XListView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Jaelyn on 2015/12/15 0015.
 * 查看退货的记录
 */
public class ScanReturnGoodsRecordsActivity extends BaseUIActivity implements ReturnOrderAdapter.ReturnOrderItemCompountClickListener {

	@ViewInject(id = R.id.xlistview_order)
	private XListView xlistview_order;
	private ReturnOrderAdapter userOrderAdapter;
	/**
	 * 无相关数据
	 */
	@ViewInject(id = R.id.nodata_layout)
	private LinearLayout nodata_layout;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.scan_returngoods_progress_layout);
		setCenter_title(R.string.return_goods_records);
		xlistview_order.setXListViewListener(xListLoadMore);
		getSearchOrder(true);
	}


	XListView.IXListViewListener xListLoadMore = new XListView.IXListViewListener() {
		@Override
		public void onRefresh() {
			getSearchOrder(true);
		}

		@Override
		public void onLoadMore() {
			getSearchOrder(false);
		}
	};


	/**
	 * 我的订单接口
	 */
	private int pageSize = 10;
	private int page = 0;
	private List<JsonMap<String, Object>> data_OrderList;
	private void getSearchOrder(boolean chearAllData) {
		loadingToast.show();
		if (chearAllData) {
			data_OrderList = null;
			if (userOrderAdapter != null) {
				userOrderAdapter.notifyDataSetChanged();
			}
			page = 0;
			xlistview_order.setPullRefreshEnable(true);
			xlistview_order.setPullLoadEnable(true);
		}
		Map<String, Object> params = new HashMap<String, Object>();
		params.put(GetDataQueue.Params_key, GetDataConfing.Key_Str);
		params.put("UserId", Utils.getUserId(this));
		params.put("currentPage", page + 1);
		params.put("pageSize", pageSize);

		GetDataQueue queue = new GetDataQueue();
		queue.setCallBack(callBack);
		queue.setActionName(GetDataConfing.Action_SelectReturnGoodsThe);
		queue.setWhat(GetDataConfing.What_SelectReturnGoodsThe);
		queue.setParamsNoJson(params);
		getDataUtil.getData(queue);
	}

	private void setAdatper_singleSortlist(final List<JsonMap<String, Object>> data) {

		if (data.size() == 0 || data.size() % pageSize != 0) {
			xlistview_order.setPullLoadEnable(false);
		}
		if (page == 0) {
			this.data_OrderList = data;
			userOrderAdapter = new ReturnOrderAdapter(this,data_OrderList);
			xlistview_order.setAdapter(userOrderAdapter);
			userOrderAdapter.setReturnOrderItemCompountClickListener(this);
		} else {
			this.data_OrderList.addAll(data);
			userOrderAdapter.notifyDataSetChanged();
		}
		page++;

	}
	/**
	 * 获取服务器数据的返回信息
	 */
	private GetServicesDataUtil.IGetServicesDataCallBack callBack = new GetServicesDataUtil.IGetServicesDataCallBack() {
		@Override
		public void onLoaded(GetServicesDataQueue entity) {
			if (entity.isOk()) {
				if (ShowGetDataError.isOkAndCodeIsNot1(mContext,
						entity.getInfo())) {
					if (entity.what == GetDataConfing.What_SelectReturnGoodsThe) {
						List<JsonMap<String, Object>> data = JsonParseHelper.getJsonMap_List_JsonMap(
								entity.getInfo(), JsonKeys.Key_Info);
						setAdatper_singleSortlist(data);
					} else if (entity.what == GetDataConfing.What_GetHistoryUserOrderByPageNum) {
						List<JsonMap<String, Object>> data = JsonParseHelper.getJsonMap_List_JsonMap(
								entity.getInfo(), JsonKeys.Key_Info);

						setAdatperDataByPageNum(data);
					} else if (entity.what == GetDataConfing.what_UpdateOrdersbyOrderNum) {
						toast.showToast(R.string.shopping_order_option_success);
						getHistoryOders();
					} else if (entity.what == GetDataConfing.What_ReturnFundByOrderNum) {
						getHistoryOders();
						toast.showToast(R.string.shopping_order_option_success);
					} else if (entity.what == GetDataConfing.What_ConfirmOrdersByOrderNum) {
						getHistoryOders();
						toast.showToast(R.string.shopping_order_option_success);

					}
				}
			} else {
				ShowGetDataError.showNetError(mContext);
			}
			loadingToast.dismiss();
			invalidateListData();
			xlistview_order.stopLoadMore();
			xlistview_order.stopRefresh();
		}
	};

	/**
	 * 设置数据 并华东到上个位置
	 *
	 * @param data
	 */
	private void setAdatperDataByPageNum(final List<JsonMap<String, Object>> data) {

		if (data.size() == 0 || data.size() % pageSize != 0) {
			xlistview_order.setPullLoadEnable(false);
		}
		this.data_OrderList = data;
		userOrderAdapter = new ReturnOrderAdapter(this, data_OrderList);
		xlistview_order.setAdapter(userOrderAdapter);
		userOrderAdapter.setReturnOrderItemCompountClickListener(this);
		if(firstItemPosition<data_OrderList.size()) {
			xlistview_order.setSelection(firstItemPosition);
		}
	}

	/**
	 * 记录当前显示的第一个item的位置
	 */
	int firstItemPosition = 0;

	/**
	 * 获取历史以查询的订单
	 */
	private void getHistoryOders() {
		getSearchOrder(true);
//        firstItemPosition = xlistview_order.getFirstVisiblePosition();
//        page = 0;
//        loadingToast.show();
//        data_OrderList = null;
//        if (userOrderAdapter != null) {
//            userOrderAdapter.notifyDataSetChanged();
//        }
//        xlistview_order.setPullRefreshEnable(true);
//        xlistview_order.setPullLoadEnable(true);
//        Map<String, Object> params = new HashMap<String, Object>();
//        params.put(GetDataQueue.Params_key,"orderCreateTime");
//        params.put("userName", Utils.getUserAccount(this));
//        params.put("currentPage", page + 1);
//        params.put("pageSize", pageSize);
//        params.put("condition",key);
//        GetDataQueue queue = new GetDataQueue();
//        queue.setCallBack(callBack);
//        queue.setActionName(GetDataConfing.GetAction_SelectOrdersBySearch);
//        queue.setWhat(GetDataConfing.what_SelectOrdersBySearch);
//        queue.setParamsNoJson(params);
//        getDataUtil.getData(queue);
	}



	private void invalidateListData() {
		if (data_OrderList == null || data_OrderList.size() < 1) {
			xlistview_order.setVisibility(View.GONE);
			nodata_layout.setVisibility(View.VISIBLE);
		} else {
			xlistview_order.setVisibility(View.VISIBLE);
			nodata_layout.setVisibility(View.GONE);
		}
	}

	@Override
	protected void onRestart() {
		super.onRestart();
		if(isNeedRefreshData) {
			getHistoryOders();
			isNeedRefreshData=false;
		}
	}


	JsonMap jsonMap;
	private boolean isNeedRefreshData=false;
	@Override
	public void returnOrderItemCompountClick(int position, Constant.UserOrderItemType userOrderItemType,int childPosition) {

		jsonMap = data_OrderList.get(position);
		String orderNum = jsonMap.getStringNoNull("OrderNum");
		String returnOrderNum=jsonMap.getStringNoNull("GoodsReturnNum"); //退货单号
		isNeedRefreshData=true;
		if(userOrderItemType== Constant.UserOrderItemType.SEE_PRODUCT){
			isNeedRefreshData=false;
			final List<JsonMap<String, Object>> dataHLV = jsonMap.getList_JsonMap("ProductList");
			String productId=dataHLV.get(childPosition).getStringNoNull("ProductId");
			seeProductDetail(productId);

		}else if (userOrderItemType == Constant.UserOrderItemType.SEELogistics) {
			isNeedRefreshData=false;
			seeLogistics(orderNum);
		} else if (userOrderItemType == Constant.UserOrderItemType.SEE_ORDER_DETAIL) {
			seeOrderDetail(orderNum);
		} else if (userOrderItemType == Constant.UserOrderItemType.CANCEL_ORDER) { //取消申请
			getData_Cancel_Order(orderNum, callBack);
		} else if (userOrderItemType== Constant.UserOrderItemType.DO_GOODS_RETURN){ //进行退货
			doGoodsReturn(returnOrderNum, jsonMap.getStringNoNull("VendorId"));
		}else if (userOrderItemType == Constant.UserOrderItemType.REFUND_DETAIL) { //退款详情
			isNeedRefreshData=false;
			scanRefundDetail(orderNum);
		} else if (userOrderItemType== Constant.UserOrderItemType.GOODS_RETURN_DETAIL){//退货详情
			isNeedRefreshData=false;
			scanReturnGoodsDetail(returnOrderNum);
		}else if(userOrderItemType== Constant.UserOrderItemType.GOODS_RETURN_PROGRESS){ //退货进度
			isNeedRefreshData=false;
			scanReturnGoodsProgress(returnOrderNum);
		}
	}

}
